﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using NSsh.Server.Services;
using System.Security.Principal;
using NSsh.Server.Utility;

namespace NSsh.Server.ChannelLayer.Console
{
    public class PowerShellConsole : BaseProcessConsole
    {
        public PowerShellConsole(IImpersonationProvider impersonationProvider, IIdentity identity, string password)
            : base(impersonationProvider, identity, password, FindPowerShell(),
            "-i Text -NoExit -Command -", Path.GetDirectoryName(FindPowerShell()))
        {
            // Show an initial prompt
            RequestPrompt();
        }

        public override void OnStandardInputData(string data)
        {
            base.OnStandardInputData(data);
            
            // Check any input data for new lines and display a prompt after those
            if (data.Contains("\r"))
            {
                RequestPrompt();
            }
        }

        public void RequestPrompt()
        {
            ProcessDetails.StandardInput.WriteLine("prompt");
            ProcessDetails.StandardInput.Flush();
        }

        public static string FindPowerShell()
        {
            string[] powerShellLocations = new string[]
            {
                Path.Combine(Environment.GetEnvironmentVariable("windir"), @"system32\WindowsPowerShell\v1.0\powershell.exe"),
                Path.Combine(Environment.GetEnvironmentVariable("windir"), @"Syswow64\WindowsPowerShell\V1.0\powershell.exe")
            };

            foreach (string powerShellLocation in powerShellLocations)
            {
                if (File.Exists(powerShellLocation)) return powerShellLocation;
            }

            return null;
        }
    }
}
